﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace CommonTools.Character
{
    public class Sign
    {
        public static string GenerateSignString(object obj, string[] continueKey = null)
        {
            var array = new Dictionary<string, string>();
            PropertyInfo[] properties = obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
            foreach (PropertyInfo item in properties)
            {
                string name = item.Name;
                if (item.GetValue(obj, null) == null || item.GetValue(obj, null).Equals("")) { continue; }
                if (continueKey != null)
                {
                    bool iscontinue = false;
                    foreach (var k in continueKey)
                    {
                        if (k.Equals(name))
                        {
                            iscontinue = true;
                            break;
                        }
                    }
                    if (iscontinue) continue;

                }

                string value = item.GetValue(obj, null).ToString();
                array.Add(name, value);
            }

            var byarray = (from v in array orderby v.Key select v).ToList();
            string signStr = "";
            foreach (var item in byarray)
            {
                signStr += string.Format("{0}={1}&", item.Key, item.Value);
            }
            signStr = signStr.TrimEnd('&');
            return signStr;
        }

        public static string GenerateSignMd5(object obj, string key, int strCase = 0, string[] noKeys = null, string[] placeKeys = null)
        {
            var signStr = GenerateSignString(obj, noKeys);
            switch (strCase)
            {
                case -1: signStr = signStr.ToLower(); break;
                case 0: break;
                case 1: signStr = signStr.ToUpper(); break;
            }
            if (placeKeys != null)
            {
                foreach (var item in placeKeys)
                {
                    signStr = signStr.Replace(item, "");
                }
            }
            var sign = Encrypt.MD5.Encrypt(string.Format("{0}{1}", signStr, key));
            return sign;
        }
    }
}
